package com.acooly.module.openapi.client.provider.weixin;

import static com.acooly.module.openapi.client.provider.weixin.OpenAPIClientWeixinProperties.PREFIX;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import com.acooly.core.utils.Ids;
import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.provider.weixin.enums.WeixinServiceEnum;
import com.acooly.module.openapi.client.provider.weixin.notify.WeixinApiServiceClientServlet;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.github.binarywang.wxpay.util.SignUtils;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;;

@EnableConfigurationProperties({OpenAPIClientWeixinProperties.class})
@ConditionalOnProperty(value = PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
@Slf4j
public class OpenAPIClientWeixinConfigration {

	@Autowired
	private OpenAPIClientWeixinProperties openAPIClientWeixinProperties;

    @Bean("wxPayService")
    public WxPayService weixinHttpTransport() {
    	WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setMchId(openAPIClientWeixinProperties.getMchId());//微信支付分配的商户号
        wxPayConfig.setAppId(openAPIClientWeixinProperties.getAppId());
        wxPayConfig.setKeyPath(openAPIClientWeixinProperties.getKeyPath());//证书路径
        wxPayConfig.setMchKey(openAPIClientWeixinProperties.getMchKey());//key
        wxPayConfig.setTradeType(null);
    	
    	WxPayService client = new WxPayServiceImpl();
    	client.setConfig(wxPayConfig);
    	log.info("init weixin client bean");
        return client;
    }

    /**
     * 微信SDK-servlet注册
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean weixinApiServiceClientServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        WeixinApiServiceClientServlet apiServiceClientServlet = new WeixinApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "weixinNotifyHandlerDispatcher");
        List<String> urlMappings = Lists.newArrayList();       //网关异步通知地址
        urlMappings.add(openAPIClientWeixinProperties.getNotifyUrl() + "/" + WeixinServiceEnum.PAY_WEIXIN_UNIFIED_ORDER.getKey());//访问，可以添加多个
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(3);
        log.info("init weixin servlet url:{}",urlMappings.toString());
        return bean;
    }
    
    public static void main(String[] args) {
    	WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setMchId("1521034891");//微信支付分配的商户号
        wxPayConfig.setAppId("wx752474a24699442b");
        wxPayConfig.setKeyPath(null);//证书路径
        wxPayConfig.setMchKey("amyBusinessManagementConsulting0");//key
        wxPayConfig.setTradeType(null);
        wxPayConfig.setUseSandboxEnv(false);
        
    	WxPayService client = new WxPayServiceImpl();
    	client.setConfig(wxPayConfig);
    	
    	try {
    		//JsPayInfo(jsAppId=wx752474a24699442b, jsTimeStamp=1557297255, jsPackage=prepay_id=wx08143419301516693beceac01776079440, jsNonceStr=BDMUSjAunFcQrbeK, sign=5026E048A79770F4790D04BC44EEFE19, signType=MD5)
    		Map<String, String> configMap = new HashMap<>();
            // 此map用于参与调起sdk支付的二次签名,格式全小写，timestamp只能是10位,格式固定，切勿修改
            configMap.put("appid", "wx752474a24699442b");
            configMap.put("noncestr", "BDMUSjAunFcQrbeK");
            configMap.put("signType", "MD5");
            configMap.put("package", "prepay_id=wx08143419301516693beceac01776079440");
            configMap.put("timestamp", "1557297255");
            //5026E048A79770F4790D04BC44EEFE19
            System.out.println("==="+SignUtils.createSign(configMap, "amyBusinessManagementConsulting0", null));
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	/**
    	try {
    		// 微信企业付款请求对象
        	WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
    		request.setDeviceInfo("WEB");//终端设备号(门店号或收银设备ID)，默认请传"WEB"
    		request.setBody("测试商品");//商品描述交易字段格式根据不同的应用场景按照以下格式：APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
    		request.setAttach(null);//附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
    		request.setOutTradeNo(Ids.oid());
    		
    		request.setTotalFee(120);
    		request.setSpbillCreateIp("127.0.0.1");
    		request.setTimeStart(null);//交易起始时间 yyyyMMddHHmmss
    		request.setTimeExpire(null);//交易结束时间 yyyyMMddHHmmss ps.repay_id只有两小时的有效期，所以在重入时间超过2小时的时候需要重新请求下单接口获取新的prepay_id
    		request.setNotifyURL("http://192.182.15.1/");
//    		if (GatewayTradeTypeEnum.WX_APP_PAY == domain.getGatewayTradeType()){
//    			request.setTradeType("APP");
//    		} else if (GatewayTradeTypeEnum.WX_JS_PAY == domain.getGatewayTradeType()){
    			request.setTradeType("JSAPI");
    			request.setOpenid("o9bFs5dDRrQgC8sS94l8a6t9kXWQ");
//    		} else if (GatewayTradeTypeEnum.WX_MASTER_SCAN_PAY == domain.getGatewayTradeType()){
//    			request.setTradeType(WxTradeTypeEnum.NATIVE.getCode());
//    			request.setProductId(domain.getGoodsMemo());
//    		} else {
//    			throw new BusinessException(GatewayResultCode.NOT_CHANNEL_ERROR,"渠道不支持的交易类型");
//    		}
    			
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = client.unifiedOrder(request);
    		
    		log.info("signkey:{}",wxPayUnifiedOrderResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
    	log.info("init weixin client bean");
	}
}
